// packageA/pages/overhaulPart/overhaulPart.js
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Dialog from '../../../miniprogram_npm/@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    //是否是修改
    isEdit:false,
    //选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //配件列表
    partList:[],
    //当前配件
    currentPart:null,
    //当前配件
    currentIndex:0,
    //日期选择框
    showDate: false,
    //当前时间
    currentDate: new Date().getTime(), 
    //最小时间
    minDate: null,
    //最大时间
    maxDate: new Date().getTime(),
    //时间格式
    formatter (type, value) {
      if (type === 'year') {
        return `${value}年`
      } else if (type === 'month') {
        return `${value}月`
      } else if (type === 'day') {
        return `${value}日`
      } else if (type === 'hour') {
        return `${value}时`
      } else if (type === 'minute') {
        return `${value}分`
      } else if (type === 'second') {
        return `${value}秒`
      }
      return value
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('检修配件传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        //获取检修数据
        this.getInfo();
      }  
    }
  },

  //提交表单##
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })
    
    let detail = e.detail.target.dataset.detail;
    let partList = this.data.partList;

    if(partList.length){
      //每一个的配件名称都要有
      let nameFlag = partList.every(item=>{
        return item.partName;
      });

      if(nameFlag){
        //验证非空
        let len = partList.length-1;
        if(partList[len].partName &&
          partList[len].factory && 
          partList[len].factory.id && 
          partList[len].replacementTime && 
          partList[len].replaceClassify &&
          partList[len].replaceClassify.id &&
          partList[len].service &&
          partList[len].service.id &&
          partList[len].factoryWarranty &&
          partList[len].factoryWarranty.id
        ){}else{
          Toast.fail('当前配件信息未完成');
          return;
        }
      }else{
        Toast.fail('配件信息未完成');
        return;
      }  

      //是否上传配件
      if(detail=='2'){
        Dialog.confirm({
          title: '确定上传此巡检工单的配件吗？',
          message: '请确认配件信息无误后再提交。\n上传后，不能再修改配件信息，\n请到设备的“更换配件明细”中查询。\n',
          confirmButtonText:'确定',
          cancelButtonText:'还要修改，暂不上传'
        }).then(() => {
          //提交表单
          this.submitForm(false);      
        }).catch(() => {
          this.submitForm(true);
        });
      }else if(detail=='1'){
        this.submitForm(true);
      }
    }else{
      Toast.fail('请添加配件');
      return;
    }
  },

  //提交表单
  submitForm(isEditPart){
    //处理配件
    let partList = this.data.partList;
    let partListNew = [];

    partList.forEach((item,index)=> {
      //处理配件图片格式
      if(item.partImg && item.partImg.length){
        let imgs = [];
        let pimg = item.partImg;
        for(let i=0;i<pimg.length;i++){
          imgs.push({
            url: pimg[i]
          });
        }
        item.partImg = imgs;
      }

      partListNew.push({
        id: index,
        part: {
          code: '',
          name: item.partName,
          specParam: ''
        },
        factory: {
          id: item.factory.id,
          name: item.factory.name,
          factoryDepart: item.factory.factoryDepart,
          UFIDACode: item.factory.UFIDACode ? item.factory.UFIDACode : ''
        },
        salePrice: Number(item.salePrice),
        num: item.num,
        remark: item.remark,
        //更换日期
        replacementTime: item.replacementTime,
        //类型
        replaceClassify: item.replaceClassify,
        //付款方
        service: item.service,
        //厂家质保
        factoryWarranty: item.factoryWarranty,
        //配件图片
        partImg: item.partImg
      });
    });

    let param={
      className:'afterSaleOverhaul',
      data:{        
        id: this.data.paramObj.id,
        parts: partListNew,
        //保存/保存并上传，加一个状态区分
        isEditPart: isEditPart
      }
    }   

    // console.log('检修配件提交');
    // console.log(param.data);
    // return;

    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');

        //配件存到更换明细表
        if(!isEditPart){
          this.savePartToEquipment(this.data.paramObj.id);
        }

        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);

      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    }) 
  },

  //获取修改数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'afterSaleOverhaul',
      data: {
        id: this.data.paramObj.id,
        selectFields: ['id','equipmentObj','parts']
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result = res.data.data.result[0];
        console.log('检修信息');
        console.log(result);

        this.setData({
          editInfo: result
        })

        //配件
        if(result.parts && result.parts.length){
          result.parts.forEach(item => {
            //名称
            item.partName = item.part.name;

            //配件图
            if(item.partImg && item.partImg.length){
              let imgs = [];
              item.partImg.forEach(item2=>{
                imgs.push(item2.url);
              });
              item.partImg = imgs;
            }
          });

          this.setData({
            partList: result.parts
          })
        }
      }
    }).catch((error) => {
    })
  },

  //显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.target.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })    

    //配件厂家
    if(field=='factory'){
      this.setData({
        selectTitle: '配件厂家',
        showSelectSearch: true,
        currentIndex: dataset.index,
        currentPart: dataset.current
      })
      this.getFactoryList();
    }

    //类型
    if(field=='replaceClassify'){
      this.setData({
        selectTitle: '类型',
        showSelectSearch: false,
        currentIndex: dataset.index,
        currentPart: dataset.current
      })
      this.getTypeList();   
    }

    //厂家质保
    if(field=='factoryWarranty'){
      this.setData({
        selectTitle: '厂家质保',
        showSelectSearch: false,
        currentIndex: dataset.index,
        currentPart: dataset.current
      })
      this.getWarrantyList();  
    }

    //付款方
    if(field=='service'){
      this.setData({
        selectTitle: '付款方',
        showSelectSearch: false,
        currentIndex: dataset.index,
        currentPart: dataset.current
      })
      this.getServiceList();  
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null; 

    //配件厂家
    if(selectField=='factory'){
      let obj=e.detail.value.obj;
      let currentIndex=this.data.currentIndex;
      let partList=this.data.partList;

      //处理配件列表
      partList.forEach((item,index) => {
        if(index==currentIndex){
          item.factory=obj;
        }
      });

      this.setData({
        partList: partList,
        disabled: false
      })
    }

    //类型
    if(selectField=='replaceClassify'){
      let obj=e.detail.value.obj;
      let currentIndex=this.data.currentIndex; 
      let partList=this.data.partList;

      //处理配件列表
      partList.forEach((item,index) => {
        if(index==currentIndex){
          item.replaceClassify=obj;
        }
      });

      this.setData({
        partList: partList,
        disabled: false
      })
    }

    //厂家质保
    if(selectField=='factoryWarranty'){
      let obj=e.detail.value.obj;
      let currentIndex=this.data.currentIndex; 
      let partList=this.data.partList;

      //处理配件列表
      partList.forEach((item,index) => {
        if(index==currentIndex){
          item.factoryWarranty=obj;
        }
      });

      this.setData({
        partList: partList,
        disabled: false
      })
    }

    //付款方
    if(selectField=='service'){
      let obj=e.detail.value.obj;
      let currentIndex=this.data.currentIndex; 
      let partList=this.data.partList;

      //处理配件列表
      partList.forEach((item,index) => {
        if(index==currentIndex){
          item.service=obj;
        }
      });

      this.setData({
        partList: partList,
        disabled: false
      })
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

    this.onCloseSelect();
  },  

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //配件厂家
    if(selectField=='factory'){
      this.getFactoryList();
    }
  },  

  //旧件退回
  onChangeReturned(event) {
    let returned='editInfo.returned';
    this.setData({
      [returned]: event.detail,
      disabled: false
    })
  },

  //添加配件
  onAddPart(){
    let partList=this.data.partList;
    
    if(partList.length){
      let len=partList.length-1;
      //未填写不能加新的
      if(partList[len].partName &&
        partList[len].factory && 
        partList[len].factory.id && 
        partList[len].replacementTime && 
        partList[len].replaceClassify &&
        partList[len].replaceClassify.id &&
        partList[len].service &&
        partList[len].service.id &&
        partList[len].factoryWarranty &&
        partList[len].factoryWarranty.id
      ){}
      else{
        Toast.fail('当前配件信息未完成');
        return;
      }
    }

    partList.push({
      id: util.timeFormat(new Date()),
      part: null,
      factory: null,
      salePrice: 0,
      num: 1,
      remark: null,
      replacementTime: util.timeFormat(new Date()),
      replaceClassify:  null,
      service: null,
      factoryWarranty: null,
      partImg: null
    });

    this.setData({ 
      partList: partList,
      disabled: false
    })
  },

  //获取配件输入的值
  onGetValue(e){
    let dataset=e.currentTarget.dataset;
    let val=e.detail;
    let partList=this.data.partList;
   
    partList.forEach((item,index) => {
      if(index==dataset.index){
        item[dataset.field]=val.trim();
      }
    }); 

    this.setData({ 
      partList: partList,
      disabled: false
		})
  },

  //删除配件
  ondeletePart(e){
    Dialog.confirm({
      title: '确认删除此配件吗',
      confirmButtonText:'确认',
      cancelButtonText:'不删除了'
    }).then(() => {
      let list = this.data.partList;
      let dataset = e.currentTarget.dataset;
      let arr = [];
      
      list.forEach((item,index) => {
        if(index!=dataset.index){
          arr.push(item);
        }
      });
  
      this.setData({ 
        partList: arr,
        disabled: false
      })
    }).catch(() => {
    });  
  },

  //查询配件厂家
  getFactoryList(){
    let param = {
      isAuth: true,
      className: 'supplierFactories',
      data: {
        searchAll: true,
        selectFields: ['id','name','factoryDepart','UFIDACode']
      }
    }
   
    if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj: item
          });
        });
        
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //获取配件数量
  onChangeNum(e) {
    let list=this.data.partList;
    let dataset=e.currentTarget.dataset;
    
    list.forEach((item,index) => {
      if(index==dataset.index){
        item.num=e.detail;
      }
    });

    this.setData({ 
      partList: list,
      disabled: false 
    })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];
   
    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  //显示日期
  onShowDate(e){
    let dataset=e.currentTarget.dataset;
    this.setData({
      showDate: true,
      currentIndex: dataset.index
    })
  },

  //隐藏日期
  onCloseDate(){
    this.setData({
			showDate: false
    })
  },

  //确认日期
  onConfirmDate(e) {
    let currentIndex=this.data.currentIndex;
    let partList=this.data.partList;
      
    partList.forEach((item,index) => {
      if(index==currentIndex){
        item.replacementTime = util.timeFormat(e.detail);
      }
    });

    this.setData({
      partList: partList,
      currentDate: e.detail,
      disabled: false
    })

    this.onCloseDate();
  },

  //取消日期（这里选择当前时间）
  onCancelDate(e){
    let currentIndex=this.data.currentIndex;
    let partList=this.data.partList;
      
    partList.forEach((item,index) => {
      if(index==currentIndex){
        item.replacementTime = util.timeFormat(new Date());
      }
    });

    this.setData({
      partList: partList,
      currentDate: new Date().getTime(),
      disabled: false
    })

    this.onCloseDate(); 
  },

  //查询类型
  getTypeList(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: "partsPurchaseClassify",
        selectFields: ['id', 'name', 'inStorage', 'outStorage', 'receivingParty', 'remark']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj: item
          });
        });
        
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询厂家质保
  getWarrantyList(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: "warrantyRanges",
        selectFields: ['id', 'name', 'num']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj: item
          });
        });
        
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //查询付款方
  getServiceList(){
    let param = {
      isAuth: false,
      className: 'dictionary',
      data: {
        searchAll: true,
        key: "paymentCompany",
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text: item.name,
            id: item.id,
            obj: item
          });
        });
        
        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
  },

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;  
    let list=this.data.partList;
    let current=data.currentTarget.dataset.current;

    list.forEach((item,index) => {
      if(item.id == current.id){
        item.partImg = imgUrls;
      }
    });

    this.setData({
      partList: list,
      disabled: false
    })
  }, 

  //配件存到更换明细表
  savePartToEquipment(id){
    let param={
      id: id
    }
    CommonService.closeOverhaulOrder(param).then(res=>{
    }).catch((error) => {
    })
  }, 

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  }
})